package algoritmoHiru;


import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class Task2 extends Thread{
	static final int portua=5555;

	public void run(){
	try {
		int mezuTamaina=1024;//jakin beharko da zein den mezuak har dezaken tamaina maximoa;
		byte [] buffer = new byte[mezuTamaina];
		DatagramSocket socketa= new DatagramSocket(portua);
		DatagramPacket paketea= new DatagramPacket(buffer,buffer.length);
		while(true){
		socketa.receive(paketea);
		//jasotako receive arraya int[] bihurtzeko. new oyek kanpoa atea??????
		MakinaBektorea makinak=MakinaBektorea.getInstance();
		if (buffer==null){//jasotako mezua hutsa bada RECOVERED mezua jaso dugu bestela LEADER mezua
			Hasieraketa.recovered[makinak.hash.get(paketea.getAddress().getHostAddress()).pos]+=Hasieraketa.zenbakiKonstantea;
		}
		else{
			
		
		ByteArrayInputStream bos = new ByteArrayInputStream(buffer);
	    ObjectInputStream oos = new ObjectInputStream(bos);
	    int[]jasotakoRecovered=(int[]) oos.readObject();
	    oos.close();
	    bos.close();
	    /**************************PROBAK*************************/
	    System.out.println("honakoa jaso da");
	    for(int x=0 ;x<jasotakoRecovered.length;x++  ){
	    	System.out.println(jasotakoRecovered[x]);
	    }
	    /**************************AMAIERA PROBAK*************************/
		
		for (int i=0;i<Hasieraketa.recovered.length;i++){
			Hasieraketa.recovered[i]=Math.max(Hasieraketa.recovered[i], jasotakoRecovered[i]);		
		}
		
		Makina unekoMakina=makinak.hash.get(paketea.getAddress().getHostAddress());
		unekoMakina.timeout=Math.max(unekoMakina.timeout, Hasieraketa.recovered[unekoMakina.pos]);
		}
	
		String bidaltzailea=paketea.getAddress().getHostName();//mejora bezela makinak konparatzeko orduan IP erabiliko dugu.
		System.out.println("pakete bidaltzailea: "+bidaltzailea);
		Hasieraketa.candidates.put(bidaltzailea,0);//candidates vectorea sortu
		Hasieraketa.update_leader();
		Hasieraketa.timer=makinak.hash.get(bidaltzailea).timeout;
		}
		
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	}
}
